# -*- coding: utf-8 -*-
from kivy.clock import Clock
from kivy.animation import Animation
from kivy.properties import NumericProperty
import model.gamestate
from ui.hat_widget import HatWidget
from ui.sound_manager import Sounds


class CountdownScreen(HatWidget):
    timeout = NumericProperty()
    red = NumericProperty(1)
    green = NumericProperty(0)

    def __init__(self, gamestate, presenter, **kwargs):
        """ Construct countdown screen
        """
        super(CountdownScreen, self).__init__(presenter, **kwargs)
        self.gamestate = gamestate
        self.timeout = presenter.settings.game.countdown_time_sec
        Clock.schedule_interval(self.update_time, 1)
        anim = (Animation(green=1, t='in_quint', duration=self.timeout / 2) +
                Animation(red=0, t='in_quint', duration=self.timeout / 2))
        anim.start(self)
        self.play_sound()

    def go_back(self):
        Clock.unschedule(self.update_time)
        self.presenter.change_phase(model.gamestate.Phase.FROM_TO)

    def update_time(self, dt):
        """change phase to GUESS_WORD
        after gamestate.settings.time_before_out_sec seconds
        """
        self.timeout -= int(round(dt))
        if self.timeout <= 0:
            self.presenter.change_phase(model.gamestate.Phase.GUESS_WORD)
            return False
        self.play_sound()

    def play_sound(self):
        if self.timeout > 1:
            self.presenter.sound_manager.play(Sounds.ShortBeep)
        else:
            self.presenter.sound_manager.play(Sounds.LongBeep)
